<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="title">活动票务管理系统</div>
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="loginRules" 
        label-position="top">
        
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
            prefix-icon="User" 
            size="large" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock" 
            size="large"
            show-password 
            @keyup.enter="handleLogin" />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            size="large"
            @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { login } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

// 表单引用
const loginFormRef = ref(null)
// 路由实例
const router = useRouter()
// 用户存储
const userStore = useUserStore()
// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: 'admin',  // 默认值便于测试
  password: '123456'  // 默认值便于测试
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 登录方法
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请正确填写登录信息')
      return false
    }
    
    loading.value = true
    
    try {
      // 1. 清除所有已存在的消息
      const existingMessages = document.querySelectorAll('.el-message')
      existingMessages.forEach(el => el.remove())
      
      // 2. 清除已有的token和存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 3. 直接发送登录请求 - 使用axios实例避免拦截器干扰
      const axios = window.axios || await import('axios').then(module => module.default)
      const loginResponse = await axios.post('/api/auth/login', {
        username: loginForm.username,
        password: loginForm.password
      })
      
      console.log('登录响应:', loginResponse)
      
      // 4. 验证响应格式
      const response = loginResponse.data
      if (!response || response.code !== 200 || !response.data) {
        throw new Error(response?.msg || '登录失败，服务器返回异常')
      }
      
      // 5. 提取并存储token和用户信息 - 严格按照方案执行
      const { token, userInfo } = response.data
      
      if (!token) {
        throw new Error('登录失败：未获取到有效的认证令牌')
      }
      
      // 6. 存储token到localStorage
      localStorage.setItem('token', token)
      
      // 7. 存储用户信息到localStorage
      if (userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      }
      
      // 8. 配置axios默认请求头 - 确保后续请求都带上token
      axios.defaults.headers.common['Authorization'] = token
      
      // 9. 更新Pinia状态 - 确保状态管理器同步
      userStore.token = token
      userStore.userInfo = userInfo || {}
      
      // 10. 显示成功消息
      ElMessage.success('登录成功')
      
      // 11. 获取重定向路径
      const redirectPath = router.currentRoute.value.query.redirect || '/event'
      
      // 12. 延迟跳转确保token已保存完成
      setTimeout(() => {
        // 13. 使用window.location硬跳转避免路由守卫问题
        window.location.href = redirectPath
      }, 800)
      
    } catch (error) {
      console.error('登录失败:', error)
      // 确保清理所有可能的残留状态
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      // 显示错误消息，确保不会被其他消息干扰
      document.querySelectorAll('.el-message').forEach(el => el.remove())
      ElMessage.error(error.message || '登录失败，请重试')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('/images/1.png') no-repeat center center;
  background-size: cover;
  position: relative;
  overflow: hidden;
}

/* 移除原有的装饰性伪元素 */
.login-container::before,
.login-container::after {
  display: none;
}

.login-card {
  width: 450px;
  padding: 30px;
  border-radius: var(--radius-large);
  box-shadow: var(--shadow-large);
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
  border: none;
  animation: fadeIn 0.5s ease-out;
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 30px;
  color: var(--text-primary);
  position: relative;
  padding-bottom: 15px;
}

.title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #5e5ce6, #7a75e3);
  border-radius: 3px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-medium);
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  border-color: var(--primary-color);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #5e5ce6;
  box-shadow: 0 0 0 2px rgba(94, 92, 230, 0.2) !important;
}

:deep(.el-input__inner) {
  height: 45px;
}

.login-button {
  width: 100%;
  height: 45px;
  border-radius: var(--radius-medium);
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(45deg, #5e5ce6, #7a75e3);
  border: none;
  box-shadow: 0 4px 10px rgba(94, 92, 230, 0.25);
  transition: all 0.3s;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(94, 92, 230, 0.35);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 500px) {
  .login-card {
    width: 90%;
    padding: 20px;
  }
}
</style> 